package com.yang.yangarmy;

import com.yang.yangarmy.utils.PingUtil;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.server.TabCompleteEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scoreboard.*;

import java.util.*;

public final class YangArmy extends JavaPlugin implements CommandExecutor, Listener {

    Map<String, String> map = new HashMap<>();

    private Scoreboard scoreboard;

    @Override
    public void onEnable() {
        // Plugin startup logic
        this.saveDefaultConfig();
        Bukkit.getPluginCommand("addArmy").setExecutor(this);
        getServer().getPluginManager().registerEvents(this, this);
        // 创建 Scoreboard
        ScoreboardManager scoreboardManager = Bukkit.getScoreboardManager();
        scoreboard = scoreboardManager.getNewScoreboard();
        Objective objective = scoreboard.registerNewObjective("playerList", "dummy", ChatColor.GREEN + "在线玩家列表");
        objective.setDisplaySlot(DisplaySlot.PLAYER_LIST);
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        Team team = scoreboard.registerNewTeam(player.getName());
        team.addEntry(player.getName());
        player.setScoreboard(scoreboard);

        // 设置玩家的称号
        String title = getTitle(player);
        team.setPrefix(title + ChatColor.RESET);
    }

    @EventHandler
    public void onTabComplete(TabCompleteEvent event) {
        // 检查是否是玩家按下 Tab 键触发的事件
        if (!(event.getSender() instanceof Player)) {
            return;
        }

        Player sender = (Player) event.getSender();
        sender.setScoreboard(scoreboard);

        // 取消默认的 Tab 补全
        event.setCancelled(true);
    }

    // 获取玩家的延迟信息（Ping）
    private int getPing(Player player) {
        // 这里可以根据需要使用不同的方法获取玩家的延迟信息
        // 这里简单地返回一个固定值 0，你可以替换成获取真实延迟信息的方法
        return PingUtil.getPing(player); // 这个方法会返回玩家的延迟，单位为毫秒
//        return 0;
    }


    @EventHandler
    public void onPlayerChat(AsyncPlayerChatEvent event) {
        Player player = event.getPlayer();
        String playerName = player.getName();

        String title = getTitle(player); // 获取玩家的称号
        String message = event.getMessage();
        ChatColor titleColor = getTitleColor(player); // 获取玩家称号的颜色

        // 构造最终显示的消息
        String formattedMessage = titleColor + title + ChatColor.RESET + playerName + ": " + message;

        // 发送最终格式化的消息
        event.setFormat(formattedMessage);
    }

    private String getTitle(Player player) {
        String playerName = player.getName();
        String armyColor = map.get(playerName);
        ChatColor color;
        switch (armyColor) {
            case "金":
                color = ChatColor.YELLOW;
                break;
            case "木":
                color = ChatColor.GREEN;
                break;
            case "水":
                color = ChatColor.BLUE;
                break;
            case "火":
                color = ChatColor.RED;
                break;
            case "土":
                color = ChatColor.GOLD;
                break;
            default:
                color = ChatColor.WHITE;
                break;
        }
        // 返回添加了颜色的称号
        return color + "[" + armyColor + "]";
    }


    // 根据玩家获取称号
    private ChatColor getTitleColor(Player player) {
        String playerName = player.getName();
        String armyColor = map.get(playerName);
        switch (armyColor) {
            case "金":
                return ChatColor.YELLOW;
            case "木":
                return ChatColor.GREEN;
            case "水":
                return ChatColor.BLUE;
            case "火":
                return ChatColor.RED;
            case "土":
                return ChatColor.GOLD;
            default:
                return ChatColor.WHITE;
        }
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!command.getName().equalsIgnoreCase("addArmy")) {
            return true;
        }
        if (args.length == 0) {
            return false;
        }
        // 监听玩家加入的是哪个队伍
        String arg = args[0];
        if (!isValidTitle(arg)) {
            sender.sendMessage(ChatColor.RED + "请输入有效的队伍名：金、木、水、火、土");
            return true;
        }
        addArmy(sender, arg);
        return true;
    }

    // 检查称号是否合法
    private boolean isValidTitle(String title) {
        Set<String> validTitles = new HashSet<>(Arrays.asList("金", "木", "水", "火", "土"));
        return validTitles.contains(title);
    }

    // 加入队伍的方法
    public void addArmy(CommandSender sender, String armyName) {
        String playerName = sender.getName();
        map.put(playerName, armyName);
        sender.sendMessage("你加入了" + armyName + "队伍");
        updateTabList();
        updatePlayerTitle((Player) sender, armyName);
    }
    public void updateTabList() {
        for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
            updatePlayerTabList(onlinePlayer);
        }
    }

    // 更新玩家的称号
    public void updatePlayerTabList(Player player) {
        // 获取玩家的延迟信息
        int ping = getPing(player);

        // 清除玩家原有的 Scoreboard
        player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard());

        // 重新设置玩家的 Scoreboard
        player.setScoreboard(scoreboard);

        // 获取玩家对应的 Team
        Scoreboard scoreboard = player.getScoreboard();
        Team team = scoreboard.getTeam(player.getName());
        if (team != null) {
            // 设置玩家的延迟信息
            ChatColor pingColor;
            if (ping <= 50) {
                pingColor = ChatColor.GREEN;
            } else if (ping <= 100) {
                pingColor = ChatColor.YELLOW;
            } else if (ping <= 150) {
                pingColor = ChatColor.RED;
            } else {
                pingColor = ChatColor.DARK_RED;
            }
            team.setSuffix(pingColor + "    " + ping + "ms" + ChatColor.RESET);
        }
    }

    // 更新玩家的称号
    private void updatePlayerTitle(Player player, String title) {
        String playerName = player.getName();
        map.put(playerName, title);

        // 获取玩家对应的 Team
        Scoreboard scoreboard = player.getScoreboard();
        Team team = scoreboard.getTeam(playerName);
        if (team == null) {
            team = scoreboard.registerNewTeam(playerName);
            team.addEntry(playerName);
        }
        // 清除旧的称号设置
        team.setPrefix("");
        // 设置玩家的称号
        team.setPrefix(getTitleColor(player) + "[" + title + "]    " + ChatColor.RESET);
    }



    @Override
    public void onDisable() {
        // Plugin shutdown logic
    }
}
